<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper">
      <a-form layout="vertical">
        <a-row :gutter="48">
          <a-col :md="8" :sm="12">
            <a-form-item label="成绩类型">
              <a-select allowClear v-model="queryParam.cjlxm">
                <a-select-option v-for="i in TYPE0328" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons" >
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button type="primary" @click="openAdd">添加</a-button>
              <a-button type="primary" @click="batchDelete">批量删除</a-button>
              <!-- <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      :pagination="{ pageSize: 10 }"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>
      <span slot="enabledFlag" slot-scope="text">
        {{ +text === 1 ? '是' : '否' }}
      </span>

      <template slot="operation" slot-scope="a,b">
        <a @click="openEdit(b)">修改</a>
      </template>
    </s-table>

    <grade-edit
      ref="gradeEdit"
      :visible.sync="visible"
      :editId.sync="editId"
      :selectMenu.sync="selectMenu"
      :confirmLoading="confirmLoading"
      @cancel="visible = false"
      @create="handleCreate"
    />
  </a-card>
</template>

<script>
import { STable } from '~'
import gradeEdit from './gradeEdit'
import { mapState } from 'vuex'

export default {
  name: 'TableList',
  components: {
    STable,
    gradeEdit
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: true,
      // 查询参数
      queryParam: {},
      postParams: {},
      // 表头
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '开始分数',
          dataIndex: 'ksfs'
        },
        {
          title: '结束分数',
          dataIndex: 'jsfs'
        },
        {
          title: '成绩类型',
          dataIndex: 'cjlxmc'
        },
        {
          title: '绩点值',
          dataIndex: 'jdz'
        },
        {
          title: '是否启用',
          dataIndex: 'enabledFlag',
          scopedSlots: { customRender: 'enabledFlag' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          width: '150px'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.base.gpaList(params).then(res => {
          return {
            data: res.data.rows,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true, // 是否显示alert，已选中
      visible: false,
      confirmLoading: false,
      editId: null,
      selectMenu: {
        cjlx: [],
        enableFlag: []
      }
    }
  },
  computed: {
    ...mapState({
      TYPE0328: state => state.app['TYPE0328']
    })
  },
  created () {
    this.$store.dispatch('app/setDictionary', 'TYPE0328')
    this.initSelectMenu()
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.dictionaryData('TYPE0328'),
        this.$api.base.dictionaryData('TYPE0346')
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          cjlx: res[0].data,
          enableFlag: res[1].data
        }
      })
    },
    handleCreate () {
      const form = this.$refs.gradeEdit.form
      form.validateFields(async (err, values) => {
        if (err) {
          return
        }
        this.confirmLoading = true
        let baseApi = this.editId ? 'gpaUpdate' : 'gpaAdd'
        let res = await this.$api.base[baseApi](Object.assign({id: this.editId}, values))
        this.$message.success(res.msg)
        this.$refs.table.refresh(false)
        this.confirmLoading = false
        // this.$api.base[baseApi](Object.assign({id: this.editId}, values)).then(res => {
        //   this.$message.success(res.msg)
        //   this.$refs.table.refresh(true)
        // })
        // if (this.editId) {
        //   this.$api.base.gpaUpdate(Object.assign({id: this.editId}, values)).then(res => {
        //     this.$message.success('修改成功')
        //     this.$refs.table.refresh(true)
        //   })
        // } else {
        //   this.$api.base.gpaAdd(values).then((res) => {
        //     this.$message.success('添加成功')
        //     this.$refs.table.refresh(true)
        //   })
        // }
        form.resetFields()
        this.visible = false
      })
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的绩点表')
        return
      }
      this.$confirm({
        title: '确定删除所选中的绩点表?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk: () => {
          let gpaIds = []
          this.selectedRows.forEach(gpa => {
            gpaIds.push(gpa.id)
          })
          this.$api.base.gpaDelete(gpaIds.join(',')).then(() => {
            this.$message.success('删除成功')
            this.selectedRowKeys = []
            this.selectedRows = []
            this.$refs.table.refresh(false)
            this.$refs.table.clearSelected()
          })
        },
        onCancel: () => {
        }
      })
      console.log(this.selectedRowKeys)
      console.log(this.selectedRows)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    openAdd () {
      this.editId = null
      this.visible = true
      this.$refs.gradeEdit.form.resetFields()
    },
    openEdit (gpa) {
      this.visible = true
      this.$refs.gradeEdit.cjlxm = gpa.cjlxm
      this.$nextTick(() => {
        this.$refs.gradeEdit.form.setFieldsValue(gpa)
        this.editId = gpa.id
      })
    }
  }
}
</script>
